import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { DateUtil } from 'src/utils'
import { Repository, Not, IsNull } from 'typeorm'
import { Admin } from '../admin/entities/admin.entity'
import { CreateNoticeDto } from './dto/create-notice.dto'
import { UpdateNoticeDto } from './dto/update-notice.dto'
import { Notice } from './entities/notice.entity'

@Injectable()
export class NoticeService {
  constructor(
    @InjectRepository(Notice) private readonly notice: Repository<Notice>,
    @InjectRepository(Admin) private readonly admin: Repository<Admin>
  ) {}
  async create(createNoticeDto: CreateNoticeDto) {
    const notice = new Notice()
    const admin = await this.admin.findOne({
      where: { id: createNoticeDto.adminId }
    })
    notice.title = createNoticeDto.title
    notice.content = createNoticeDto.content
    notice.admin = admin
    notice.status = createNoticeDto.status
    notice.date = new DateUtil(new Date(), 'yyyy-MM-dd hh:mm:ss').format()
    return this.notice.save(notice)
  }

  async findAll(params: {
    page: number
    pageSize: number
    isDelete?: boolean
    status?: string
  }) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    params.status && (where['status'] = params.status)
    const data = await this.notice.find({
      where: { ...where },
      relations: ['admin'],
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize,
      order: { id: 'DESC' }
    })
    const total = await this.notice.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    const newData = []
    data.forEach(item => {
      const { admin, ...rest } = item
      const newItem = {
        ...rest,
        admin: admin.name
      }
      newData.push(newItem)
    })
    return { data: newData, total }
  }

  async findOne(id: number) {
    return await this.notice.findOne({ where: { id } })
  }

  update(id: number, updateNoticeDto: UpdateNoticeDto) {
    const date = new DateUtil(new Date(), 'yyyy-MM-dd hh:mm:ss').format()
    return this.notice.update(id, { ...updateNoticeDto, date })
  }

  remove(ids: number[]) {
    return this.notice.softDelete(ids)
  }

  restore(ids: number[]) {
    return this.notice.restore(ids)
  }
}
